package br.com.digitalizar.relproducao.core;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.InvalidAspectException;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.search.LimitBy;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.bean.search.SearchContext;

import br.com.digitalizar.pdfpages.PDFPagesAspect;
import br.com.digitalizar.relproducao.bean.ReportBean;

/**
 * Class responsible for digging the repository in search of the number of pages per document.
 * She still has a method to summarize the research and return a bean to be displayed on the screen.
 * 
 * It is the heart of this module
 * 
 * @author Rafael de Morais
 *
 */
public class Digger {
	
	/**
	 * The SearchService
	 */
	private SearchService searchService;
	
	/**
	 * The NodeService
	 */
	private NodeService nodeService;
	
	private DictionaryService dictionaryService;
	
	private Collection<QName> listTypes;
	
	private Map<QName, ReportBean> reports;
	
	protected Date startDate = Calendar.getInstance().getTime();
	protected Date endDate = Calendar.getInstance().getTime();
	
	public Digger(SearchService searchService, NodeService nodeService, DictionaryService dictionaryService) {
		//TODO tratar parametro null
		this.searchService = searchService;
		this.nodeService = nodeService;
		this.dictionaryService = dictionaryService;
		reports = new HashMap<QName, ReportBean>();
	}
	
	public void performSearch() {
		
		List<NodeRef> nodes = new ArrayList<NodeRef>();
		
		for (QName qname : listTypes) {
			SearchParameters sp = new SearchParameters();
			sp.setLanguage(SearchService.LANGUAGE_LUCENE);
			
			sp.setQuery(buildSearchContext(qname).buildQuery(0));
			
			System.out.println(qname);//REMOVER
			
			sp.addStore(Repository.getStoreRef());
			
			sp.setLimitBy(LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS);
			sp.setLimit(0);
			
			ResultSet rs = searchService.query(sp);
			
			nodes.addAll(rs.getNodeRefs());
		}
		
		ReportBean report;
		Integer np;
		
		for (NodeRef nodeRef : nodes) {
			try {
				if(nodeService.hasAspect(nodeRef, PDFPagesAspect.ASPECT)) {
					
					if(reports.containsKey(nodeService.getType(nodeRef))) {
						report = reports.get(nodeService.getType(nodeRef));
					}else {
						report = new ReportBean();
						report.setSumDocs(0L);
						report.setSumPages(0L);
						report.setType(dictionaryService.getType(nodeService.getType(nodeRef)).getTitle());
						
						reports.put(nodeService.getType(nodeRef), report);
					}
					
					np = (Integer) nodeService.getProperty(nodeRef, PDFPagesAspect.PROP_NUMBER_OF_PAGES);
					report.setSumPages(report.getSumPages() + np);
					report.setSumDocs(report.getSumDocs()+ 1);
				}
			} catch (InvalidNodeRefException e) {
				e.printStackTrace();
			} catch (InvalidAspectException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private SearchContext buildSearchContext(QName contentType) {
		SearchContext s = new SearchContext();
		
		s.setMode(SearchContext.SEARCH_ALL);
		
		//Range
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		String strFromDate = df.format(startDate);
		String strToDate = df.format(endDate);
		s.addRangeQuery(ContentModel.PROP_CREATED, strFromDate, strToDate, true);
		
		s.setContentType(contentType.toString());
		
		return s;
	}
	
	public void setRange(Date from, Date to) {
		this.startDate = from;
		this.endDate = to;
	}
	
	public void setContentTypes(Collection<QName> listTypes) {
		this.listTypes = listTypes;
	}
	
	public List<ReportBean> getReportBeans() {
		List<ReportBean> l = new ArrayList<ReportBean>();
		l.addAll(reports.values());
		return l;
	}
}